Browse Source

second commit

pull/1/head
dewjjj 8 months ago
parent
commit
932dbcad59
  1. 1
      .gitignore
  2. BIN
      fetchall/fetchall
  3. 38
      fetchall/fetchall.go
  4. 6
      hello/hello.go
  5. BIN
      os.Args/os.Args
  6. 11
      os.Args/os.Args.go
  7. 15
      server0/server0.go
  8. 29
      server1/server1.go
  9. 32
      server2/server2.go

1
.gitignore

@ -0,0 +1 @@
.DS_Store

BIN
fetchall/fetchall

Binary file not shown.

38
fetchall/fetchall.go

@ -0,0 +1,38 @@
package main
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"time"
)
func main(){
start := time.Now()
ch := make(chan string)
for _,url := range os.Args[1:]{
go fetch(url,ch)
}
for range os.Args[1:]{
fmt.Println(<-ch)
}
fmt.Printf("%.2fs elapsed\n",time.Since(start).Seconds())
}
func fetch(url string,ch chan<- string) {
start := time.Now()
resp,err := http.Get(url)
if err != nil {
ch <- fmt.Sprint(err)
return
}
nbytes,err := io.Copy(ioutil.Discard,resp.Body)
resp.Body.Close()
if err != nil{
ch <- fmt.Sprintf("while reading %s: %v",url,err)
return
}
secs := time.Since(start).Seconds()
ch <- fmt.Sprintf("%.2fs %7d %s",secs,nbytes,url)
}

6
hello/hello.go

@ -0,0 +1,6 @@
package main
import "fmt"
func main(){
fmt.Println("Hello, 界!")
}

BIN
os.Args/os.Args

Binary file not shown.

11
os.Args/os.Args.go

@ -0,0 +1,11 @@
package main
import (
"fmt"
"os"
)
func main(){
for num,url :=range os.Args{
fmt.Printf("%d: %s\n",num,url)
}
}

15
server0/server0.go

@ -0,0 +1,15 @@
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe("localhost:8000", nil))
}
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "URL.Path= %q\n", r.URL.Path)
}

29
server1/server1.go

@ -0,0 +1,29 @@
package main
import (
"fmt"
"log"
"net/http"
"sync"
)
var mu sync.Mutex
var count int
func main() {
http.HandleFunc("/", handler)
http.HandleFunc("/count", counter)
log.Fatal(http.ListenAndServe("localhost:8000", nil))
}
func handler(w http.ResponseWriter, r *http.Request) {
mu.Lock()
count++
mu.Unlock()
fmt.Fprintf(w, "URL.Path= %q\n", r.URL.Path)
}
func counter(w http.ResponseWriter, r *http.Request) {
mu.Lock()
fmt.Fprintf(w, "Count %d\n", count)
mu.Unlock()
}

32
server2/server2.go

@ -0,0 +1,32 @@
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe("localhost:8000", nil))
}
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "%s %s %s\n", r.Method, r.URL, r.Proto)
for k, v := range r.Header {
fmt.Fprintf(w, "Header[%q] = %q\n", k, v)
}
fmt.Fprintf(w, "Host = %q\n", r.Host)
fmt.Fprintf(w, "RemoteAddr = %q\n", r.RemoteAddr)
if err := r.ParseForm(); err != nil {
log.Print(err)
}
r.ParseForm()/*
http://localhost:8000/?q=query,
此时得到的map中的key,value就是q,query
*/
fmt.Println(r.Form)
for k, v := range r.Form {
fmt.Fprintf(w, "Form[%q] = %q\n", k, v)
}
}
Loading…
Cancel
Save