Created
May 15, 2016 20:37
-
-
Save xamgore/c59cd1add832d2720f809361bf15c455 to your computer and use it in GitHub Desktop.
Light http over tcp server as an example of net package in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ("fmt"; "io"; "net"; "strings"; "sync/atomic") | |
var clientsCount int64 = 0 | |
func main() { | |
server, _ := net.Listen("tcp", "127.0.0.1:28563") | |
defer server.Close() | |
for { | |
connection, err := server.Accept() | |
if (err == nil) { go processClient(connection) } | |
} | |
} | |
func processClient(socket net.Conn) { | |
atomic.AddInt64(&clientsCount, 1); defer atomic.AddInt64(&clientsCount, -1) | |
fmt.Printf("%d concurrent clients are connected\n", atomic.LoadInt64(&clientsCount)) | |
toProcess, buffer := "", make([]byte, 2048) | |
defer socket.Close() | |
for { | |
count, err := socket.Read(buffer) | |
if err == io.EOF || count == 0 { | |
break // client closed the connection | |
} | |
request := toLF(string(buffer[:count])) | |
queries := strings.Split(toProcess + request, "\n\n") | |
toProcess, queries = queries[len(queries)-1], queries[:len(queries)-1] | |
for _, query := range queries { | |
// Return an HTTP-answer with the 8th char of the original request | |
socket.Write([]byte("HTTP/1.1 200 OK\nServer: super fast mexmat server\nContent-Type: text/html\nContent-Length: 1\n\n")) | |
if len(query) > 7 { | |
socket.Write([]byte{ query[7] }) | |
} | |
} | |
} | |
} | |
func toLF(s string) string { return strings.Replace(s, "\r\n", "\n", -1) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment