Skip to content

Instantly share code, notes, and snippets.

@siburu
Last active December 1, 2015 09:34
Show Gist options
  • Save siburu/143de464ab8579ab3eff to your computer and use it in GitHub Desktop.
Save siburu/143de464ab8579ab3eff to your computer and use it in GitHub Desktop.
/*
A HTTP*S* server.
The path /ws is special, dedicated for WebSocket connection.
The other paths work as ordinary (non-WebSocket) resource.
*/
package main
import (
"crypto/tls"
"encoding/json"
"log"
"net/http"
"time"
"github.com/gorilla/websocket"
)
type Response struct {
Time time.Time `json:"time"`
URL string `json:"url"`
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 4096,
WriteBufferSize: 4096,
}
func main() {
cert, err := tls.LoadX509KeyPair("ca.crt", "ca.key")
if err != nil {
log.Fatalf("tls.LoadX509KeyPair: %v\n", err)
}
conf := tls.Config{Certificates: []tls.Certificate{cert}}
listener, err := tls.Listen("tcp", ":8443", &conf)
if err != nil {
log.Fatalf("tls.Listen: %v\n", err)
}
mux := http.NewServeMux()
mux.HandleFunc("/", handleRoot)
mux.HandleFunc("/ws", handleWs)
err = http.Serve(listener, mux)
if err != nil {
log.Fatalf("http.Serve: %v\n", err)
}
log.Println("OK")
}
func handleRoot(w http.ResponseWriter, r *http.Request) {
res := Response{
Time: time.Now(),
URL: r.URL.Path,
}
data, err := json.Marshal(res)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
} else {
w.Header().Set("content-type", "application/json")
w.Write(data)
}
}
func handleWs(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
return
}
res := Response{
Time: time.Now(),
URL: r.URL.Path,
}
err = conn.WriteJSON(&res)
if err != nil {
log.Fatalf("conn.WriteJSON: %v\n", err)
}
err = conn.Close()
if err != nil {
log.Fatalf("conn.Close: %v\n", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment