zoukankan      html  css  js  c++  java
  • Go Pentester

    HTTP Server Basics

    Use net/http package and useful third-party packages by building simple servers.

    Building a Simple Server

    package main
    
    import (
    	"fmt"
    	"net/http"
    )
    
    func hello(w http.ResponseWriter, r *http.Request) {
    	fmt.Fprintf(w, "Hello %s
    ", r.URL.Query().Get("name"))
    }
    
    func main() {
    	http.HandleFunc("/hello", hello)
    	http.ListenAndServe(":8000",nil)
    }
    

    Run the above program and test it.

    curl -i http://localhost:8000/hello?name=eric
    

     You can also use http.ListenAndServeTLS(), which will start a server using HTTPS and TLS.

    Build a Simple Router

    package main
    
    import (
    	"fmt"
    	"net/http"
    )
    
    type router struct {
    }
    
    func (r *router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    	switch req.URL.Path {
    	case "/a":
    		fmt.Fprintf(w, "Executing /a
    ")
    	case "/b":
    		fmt.Fprintf(w, "Executing /b
    ")
    	case "/c":
    		fmt.Fprintf(w, "Executing /c
    ")
    	default:
    		http.Error(w, "404 Not Found", 404)
    	}
    }
    
    func main() {
    	var r router
    	http.ListenAndServe(":8000", &r)
    }
    

    Test the above program by the following commands.

    curl http://localhost:8000/a
    curl http://localhost:8000/d

    Building simple Middleware

    A simple middleware, which is a sort of wrapper that will execute on all incoming requests regardless of the destination function.

    package main
    
    import (
    	"fmt"
    	"log"
    	"net/http"
    	"time"
    )
    
    type logger struct {
    	Inner http.Handler
    }
    
    func (l *logger) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    	log.Printf("start %s
    ", time.Now().String())
    	l.Inner.ServeHTTP(w,r)
    	log.Printf("finish %s",time.Now().String())
    }
    
    func hello(w http.ResponseWriter, r *http.Request) {
    	fmt.Fprint(w, "Hello
    ")
    }
    
    func main() {
    	f := http.HandlerFunc(hello)
    	l := logger{Inner: f}
    	http.ListenAndServe(":8000", &l)
    }
    

    Run the program and issue a request.

    curl http://localhost:8000

    相信未来 - 该面对的绝不逃避,该执著的永不怨悔,该舍弃的不再留念,该珍惜的好好把握。
  • 相关阅读:
    毕业3年在北京买房,他是怎么赚钱攒钱的?
    Windows Server 2008 如何在IIS中添加MIME类型
    IIS下无法访问.ini后缀文件
    新的一年,我们如何才能收获满满,不留太多遗憾呢?
    你百分之九十九的问题都是因为懒
    为什么你容许陌生人成功,却无法忍受身边人发达
    堆排序
    计数排序
    直接插入排序
    冒泡排序
  • 原文地址:https://www.cnblogs.com/keepmoving1113/p/12398127.html
Copyright © 2011-2022 走看看