zoukankan      html  css  js  c++  java
  • Go搭建一个Web服务器

    我们可以使用http包建立Web服务器

     1 package main
     2 
     3 import (
     4     "fmt"
     5     "log"
     6     "strings"
     7     "net/http"
     8 )
     9 
    10 func sayHelloName(w http.ResponseWriter,r *http.Request){
    11     r.ParseForm() // 解析参数
    12     fmt.Println(r.Form)
    13     fmt.Println("path",r.URL.Path)
    14     fmt.Println("scheme",r.URL.Scheme)
    15     fmt.Println(r.Form["url_long"])
    16     for k,v := range r.Form{
    17         fmt.Println("key",k)
    18         fmt.Println("val",strings.Join(v,""))
    19     }
    20     fmt.Fprintf(w,"Hello astaxie!")
    21 }
    22 
    23 func main(){
    24     http.HandleFunc("/",sayHelloName) // 设置访问的路由
    25     err := http.ListenAndServe(":9090",nil) // 设置监听的端口
    26     if err != nil{
    27         log.Fatal("ListenAndServer Failed:",err)
    28     }
    29 }

    上面这个代码,我们build之后,然后执行web.exe,这个时候其实已经在9090端口监听http链接请求了。

    在浏览器输入http://localhost:9090

    可以看到浏览器页面输出了Hello astaxie!

    可以换一个地址试试:http://localhost:9090/?url_long=111&url_long=222

    看看浏览器输出的是什么,服务器输出的是什么?

    在服务器端输出的信息如下:

    用户访问Web之后服务器端打印的信息

    我们看到上面的代码,要编写一个Web服务器很简单,只要调用http包的两个函数就可以了。

  • 相关阅读:
    HDU1316 fib+高精度
    HDU1868
    HDU2586 LCA
    HDU1113 字符串处理
    HDU1115 几何+多边形重心
    HDU1124
    HDU1110 几何
    HDU1103
    HDU2670 DP
    linux 下查看机器是cpu是几核的
  • 原文地址:https://www.cnblogs.com/Mikusa/p/12132501.html
Copyright © 2011-2022 走看看