lundi 29 juin 2015

How do use go lang as a web server

I have recently look into go lang and decided that it would be the best option to further improve the speed of the my website and handle more request. As php is not very efficient. In go lang i can write a script which runs multiple go lang webpage (it will host multiple page in a website). However all the page detial and code has to be in the one file.

My current code:

    package main

import (
    "fmt"
    "net/http"
    "strings"
    "log"
    "os"
    "strconv"
    "io"
)

func sayhelloName(w http.ResponseWriter, r *http.Request) {
    r.ParseForm()  // parse arguments, you have to call this by yourself
    fmt.Println(r.Form)  // print form information in server side
    fmt.Println("path", r.URL.Path)
    fmt.Println("scheme", r.URL.Scheme)
    fmt.Println(r.Form["url_long"])
    for k, v := range r.Form {
        fmt.Println("key:", k)
        fmt.Println("val:", strings.Join(v, ""))
    }
    fmt.Fprintf(w, "Hello User!") // send data to client side
}
func main() {
    http.HandleFunc("/hello", sayhelloName) // set router    
err := http.ListenAndServe(":900", nil) // set listen port
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

As you can see this script will host the page which is myip:900/hello and it will print hello. If i type myip:/hello/person it will say hello person ect.

However my script from the hello world page, (at the moment) has to also be in the same script as this.

Basically, i would like to have a go lang script which handles the request and send them to another script which will be run and provide a the page - if possible can you demonstrate exemplar code for both pages. Additionally is it possible for go to host some php page passing the url to the php manger fastcgi. So that I can switch over my server to go lang fast server - whilst i convert my php code into go lang code - however this is not vital (just useful).

Also would it be better to program a website in java or go lang. If java can you show an example code please.




Aucun commentaire:

Enregistrer un commentaire