利用Go生成简易的Web Server

采用Golang生成Web Server无需额外处理相关的静态文件等引用,会减少代码量和维护工作量

 1package main
 2
 3import (
 4	"encoding/json"
 5	"io/ioutil"
 6	"log"
 7	"net/http"
 8	"os"
 9	"strconv"
10)
11
12type ConfigData struct {
13	Info string `json:"info"`
14	File string `json:"file"`
15	Port int    `json:"port"`
16}
17
18func parseConfigFile() ConfigData {
19	jsonFile, err := os.Open("config.json")
20	if err != nil {
21		log.Println(err)
22	}
23	log.Println("Successfully Opened config.json")
24
25	defer jsonFile.Close()
26
27	byteValue, _ := ioutil.ReadAll(jsonFile)
28
29	var config ConfigData
30	err = json.Unmarshal(byteValue, &config)
31	if err != nil {
32		log.Fatal(err)
33	}
34	return config
35}
36
37func main() {
38	var config = parseConfigFile()
39	log.Println("port: " + strconv.Itoa(config.Port))
40	log.Println("file: " + config.File)
41	log.Println(config.Info)
42	log.Println("可通过 http://127.0.0.1:" + strconv.Itoa(config.Port) + " 访问此系统")
43
44	http.Handle("/", http.FileServer(http.Dir(config.File)))
45	http.ListenAndServe(":"+strconv.Itoa(config.Port), nil)
46}