Go实现http服务器


package main

import (
	"bytes"
	"io"
	"net/http"
)

func DefaultHandler(w http.ResponseWriter, req *http.Request) {

	var HtmlBuffer bytes.Buffer

	HtmlBuffer.WriteString("HTTP Method : ")
	HtmlBuffer.WriteString(req.Method)

	HtmlBuffer.WriteString("\nHTTP Proto : ")
	HtmlBuffer.WriteString(req.Proto)

	HtmlBuffer.WriteString("\nhttp Host : ")
	HtmlBuffer.WriteString(req.Host)

	HtmlBuffer.WriteString("\nRequest RemoteAddr : ")
	HtmlBuffer.WriteString(req.RemoteAddr)

	HtmlBuffer.WriteString("\nRequestURI : ")
	HtmlBuffer.WriteString(req.RequestURI)

	io.WriteString(w, HtmlBuffer.String())
}

func HttpServer(port string) {
	http.HandleFunc("/", DefaultHandler)
	http.ListenAndServe(port, nil)
}

func main() {
	HttpServer(":8080")
}

最简版本:


package main

import (
	"net/http"
)

func DefaultHandler(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("Hello World!"))
}

func main() {
	http.HandleFunc("/", DefaultHandler)
	http.ListenAndServe(":8000", nil)
}

带信号控制的版本:

package main

import (
	"context"
	"net/http"
	"os"
	"os/signal"
	"time"
)

func defaultHandler(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("Hello World!"))
}

func main() {
	shutdownSign := make(chan os.Signal)
	signal.Notify(shutdownSign, os.Interrupt)

	mux := http.NewServeMux()
	mux.HandleFunc("/", defaultHandler)

	var server *http.Server

	server = &http.Server{
		Addr:         ":8000",
		WriteTimeout: time.Second * 5,
		Handler:      mux,
	}

	go func() {
		<-shutdownSign
		server.Shutdown(context.Background())
	}()

	server.ListenAndServe()
}