How to use notFound method of td Package

Best Go-testdeep code snippet using td.notFound

http.go

Source:http.go Github

copy

Full Screen

1package http2import (3 "bytes"4 "context"5 "errors"6 "fmt"7 "html"8 "io"9 "net"10 "net/http"11 "net/url"12 "os"13 "sort"14 "strconv"15 "strings"16 "time"17 "github.com/jech/storrent/alloc"18 "github.com/jech/storrent/config"19 "github.com/jech/storrent/dht"20 "github.com/jech/storrent/hash"21 "github.com/jech/storrent/known"22 "github.com/jech/storrent/path"23 "github.com/jech/storrent/peer"24 "github.com/jech/storrent/tor"25 "github.com/jech/storrent/tracker"26)27type handler struct {28 ctx context.Context29}30func NewHandler(ctx context.Context) http.Handler {31 return &handler{ctx}32}33func (handler *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {34 host, _, err := net.SplitHostPort(r.Host)35 if err != nil {36 http.Error(w, err.Error(), http.StatusBadRequest)37 return38 }39 // The server is only bound to localhost, but an attacker might be40 // able to cause the user's browser to connect to localhost by41 // manipulating the DNS. Prevent this by making sure that the42 // browser thinks it's connecting to localhost.43 if host != "localhost" && net.ParseIP(host) == nil {44 http.Error(w, "Forbidden", http.StatusForbidden)45 return46 }47 pth := r.URL.Path48 if pth == "/" {49 root(handler.ctx, w, r)50 return51 }52 if len(pth) < 41 {53 http.NotFound(w, r)54 return55 }56 hash := hash.Parse(pth[1:41])57 if hash == nil {58 http.NotFound(w, r)59 return60 }61 if r.Method != "HEAD" && r.Method != "GET" {62 w.Header().Set("allow", "HEAD, GET")63 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)64 return65 }66 if len(pth) == 41 {67 t := tor.Get(hash)68 if t == nil {69 http.NotFound(w, r)70 return71 }72 http.Redirect(w, r, pth+"/", http.StatusMovedPermanently)73 return74 }75 if pth[41] == '/' {76 err = r.ParseForm()77 if err != nil {78 http.Error(w, err.Error(), http.StatusBadRequest)79 return80 }81 if r.Form["playlist"] != nil {82 playlist(w, r, hash, path.Parse(pth[42:]))83 return84 }85 if pth[len(pth)-1] == '/' {86 directory(w, r, hash, path.Parse(pth[42:]))87 return88 } else {89 file(w, r, hash, path.Parse(pth[42:]))90 return91 }92 }93 if pth[41] == '.' {94 extension := pth[42:]95 if extension == "torrent" {96 torfile(w, r)97 return98 } else if extension == "m3u" {99 playlist(w, r, hash, nil)100 return101 }102 }103 http.NotFound(w, r)104}105func getTorrent(ctx context.Context, data string) (*tor.Torrent, error) {106 t, err := tor.ReadMagnet(config.DefaultProxy(), data)107 if t != nil || err != nil {108 return t, err109 }110 return tor.GetTorrent(ctx, config.DefaultProxy(), data)111}112func root(serverctx context.Context, w http.ResponseWriter, r *http.Request) {113 if r.Method != "HEAD" && r.Method != "GET" && r.Method != "POST" {114 w.Header().Set("allow", "HEAD, GET, POST")115 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)116 return117 }118 err := r.ParseForm()119 if err != nil {120 http.Error(w, err.Error(), http.StatusBadRequest)121 return122 }123 q := r.Form.Get("q")124 if q == "" {125 if r.Method != "HEAD" && r.Method != "GET" {126 http.Error(w, "Method not allowed",127 http.StatusMethodNotAllowed)128 return129 }130 torrents(w, r)131 return132 } else if q == "peers" {133 if r.Method != "HEAD" && r.Method != "GET" {134 http.Error(w, "Method not allowed",135 http.StatusMethodNotAllowed)136 return137 }138 hash := hash.Parse(r.Form.Get("hash"))139 if hash == nil {140 http.NotFound(w, r)141 return142 }143 torrent := tor.Get(hash)144 if torrent == nil {145 http.NotFound(w, r)146 return147 }148 peers(w, r, torrent)149 return150 } else if q == "add" {151 data := strings.TrimSpace(r.FormValue("url"))152 if data == "" {153 http.Error(w, "No torrent supplied", http.StatusBadRequest)154 return155 }156 t, err := getTorrent(r.Context(), data)157 if t == nil || err != nil {158 http.Error(w, err.Error(), http.StatusBadGateway)159 return160 }161 _, err = tor.AddTorrent(serverctx, t)162 if err != nil && err != os.ErrExist {163 http.Error(w, err.Error(),164 http.StatusInternalServerError)165 return166 }167 http.Redirect(w, r, "/", http.StatusSeeOther)168 return169 } else if q == "delete" {170 h := hash.Parse(r.FormValue("hash"))171 if h == nil {172 http.Error(w, "couldn't parse hash", http.StatusBadRequest)173 return174 }175 t := tor.Get(h)176 if t == nil {177 http.NotFound(w, r)178 return179 }180 err := t.Kill(r.Context())181 if err != nil {182 if errors.Is(err, tor.ErrTorrentDead) {183 http.NotFound(w, r)184 } else {185 http.Error(w, err.Error(),186 http.StatusInternalServerError)187 }188 return189 }190 http.Redirect(w, r, "/", http.StatusSeeOther)191 return192 } else if q == "set" {193 upload := r.Form.Get("upload")194 if upload != "" {195 v, err := strconv.ParseFloat(upload, 64)196 if err != nil {197 http.Error(w, err.Error(), http.StatusBadRequest)198 return199 }200 config.SetUploadRate(v)201 }202 idle := r.Form.Get("idle")203 if idle != "" {204 v, err := strconv.ParseFloat(idle, 64)205 if err != nil {206 http.Error(w, err.Error(), http.StatusBadRequest)207 return208 }209 config.SetIdleRate(v)210 }211 http.Redirect(w, r, "/", http.StatusSeeOther)212 return213 } else if q == "set-torrent" {214 h := hash.Parse(r.FormValue("hash"))215 if h == nil {216 http.Error(w, "couldn't parse hash", http.StatusBadRequest)217 return218 }219 t := tor.Get(h)220 if t == nil {221 http.NotFound(w, r)222 return223 }224 conf := peer.TorConf{225 UseDht: peer.ConfGet(r.Form.Get("use-dht") != ""),226 DhtPassive: peer.ConfGet(r.Form.Get("dht-passive") != ""),227 UseTrackers: peer.ConfGet(r.Form.Get("use-trackers") != ""),228 UseWebseeds: peer.ConfGet(r.Form.Get("use-webseeds") != ""),229 }230 err = t.SetConf(conf)231 if err != nil {232 http.Error(w, err.Error(),233 http.StatusInternalServerError)234 return235 }236 http.Redirect(w, r, "/", http.StatusSeeOther)237 return238 } else {239 http.Error(w, "Bad request", http.StatusBadRequest)240 return241 }242}243func header(w http.ResponseWriter, r *http.Request, title string) bool {244 w.Header().Set("content-type", "text/html; charset=utf-8")245 w.Header().Set("cache-control", "no-cache")246 if r.Method == "HEAD" {247 return true248 }249 fmt.Fprintf(w, "<!DOCTYPE html>\n<html><head>\n")250 fmt.Fprintf(w, "<title>%v</title>\n", html.EscapeString(title))251 if r.Host != "" {252 fmt.Fprintf(w, "<script type=\"text/javascript\">\n")253 fmt.Fprintf(w, "navigator.registerProtocolHandler('magnet','http://%v/?q=add&url=%%s','Torrent');\n",254 r.Host)255 fmt.Fprintf(w, "</script>\n")256 }257 fmt.Fprintf(w, "</head><body>\n")258 return false259}260func footer(w http.ResponseWriter) {261 fmt.Fprintf(w, "</body></html>\n")262}263func directory(w http.ResponseWriter, r *http.Request, hash hash.Hash, pth path.Path) {264 ctx := r.Context()265 t := tor.Get(hash)266 if t == nil {267 http.NotFound(w, r)268 return269 }270 done := header(w, r, t.Name)271 if done {272 return273 }274 err := torrentEntry(ctx, w, t, pth)275 if err != nil {276 return277 }278 footer(w)279}280func pathUrl(p path.Path) string {281 var b []byte282 for _, s := range p {283 t := url.PathEscape(s)284 b = append(b, t...)285 b = append(b, '/')286 }287 return string(b[0 : len(b)-1])288}289func torrentFile(w io.Writer, hash hash.Hash, path path.Path, length int64, available int) {290 p := pathUrl(path)291 fmt.Fprintf(w,292 "<tr><td><a href=\"/%v/%v\">%v</a></td>"+293 "<td>%v</td><td>%v</td></tr>\n",294 hash, p, html.EscapeString(path.String()),295 length, available)296}297func torrentDir(w io.Writer, hash hash.Hash, pth path.Path, lastdir path.Path) {298 var dir path.Path299 for i := 0; i < len(pth) && i < len(lastdir); i++ {300 if pth[i] != lastdir[i] {301 break302 }303 dir = append(dir, pth[i])304 }305 for i := len(dir); i < len(pth); i++ {306 dir = append(dir, pth[i])307 p := pathUrl(dir)308 fmt.Fprintf(w,309 "<tr><td><a href=\"/%v/%v/\">%v/</a></td><td>"+310 "(<a href=\"/%v/%v/?playlist\">playlist</a>)"+311 "</td></tr>\n",312 hash, p, html.EscapeString(dir.String()),313 hash, p)314 }315}316func torrentEntry(ctx context.Context, w http.ResponseWriter, t *tor.Torrent, dir path.Path) error {317 hash := t.Hash318 name := t.Name319 if !t.InfoComplete() {320 if name != "" {321 name = name + " "322 }323 name = name + "<em>(incomplete)</em>"324 }325 fmt.Fprintf(w, "<p><a href=\"/%v/\">%v</a> ", hash, name)326 fmt.Fprintf(w, "<a href=\"/%v.torrent\">%v</a> ", hash, hash)327 fmt.Fprintf(w, "(<a href=\"/%v.m3u\">playlist</a>): ", hash)328 c := t.Pieces.Bitmap().Count()329 if t.InfoComplete() {330 fmt.Fprintf(w, "%v bytes in %v+%v/%v pieces (%v bytes each), ",331 t.Pieces.Bytes(),332 c, t.Pieces.Count()-c,333 (t.Pieces.Length()+int64(t.Pieces.PieceSize())-1)/334 int64(t.Pieces.PieceSize()),335 t.Pieces.PieceSize())336 }337 stats, _ := t.GetStats()338 if stats != nil {339 fmt.Fprintf(w, "<a href=\"/?q=peers&hash=%v\">%v/%v peers</a>",340 hash, stats.NumPeers, stats.NumKnown)341 }342 fmt.Fprintf(w, "</p>")343 fmt.Fprintf(w, "<p><table>\n")344 if !t.InfoComplete() {345 } else if t.Files == nil {346 if err := ctx.Err(); err != nil {347 return err348 }349 if len(dir) == 0 {350 available, _ := t.GetAvailable()351 torrentFile(w, t.Hash, path.Parse(t.Name),352 t.Pieces.Length(),353 available.AvailableRange(t,354 0, t.Pieces.Length()))355 }356 } else {357 a := make([]int, 0, len(t.Files))358 for i := range t.Files {359 if t.Files[i].Path.Within(dir) {360 a = append(a, i)361 }362 }363 sort.Slice(a, func(i, j int) bool {364 return t.Files[a[i]].Path.Less(t.Files[a[j]].Path)365 })366 var lastdir path.Path367 available, _ := t.GetAvailable()368 for _, i := range a {369 if err := ctx.Err(); err != nil {370 return err371 }372 f := t.Files[i]373 path := f.Path374 dir := path[:len(path)-1]375 if !dir.Equal(lastdir) {376 torrentDir(w, t.Hash, dir, lastdir)377 lastdir = dir378 }379 torrentFile(w, t.Hash, f.Path, f.Length,380 available.AvailableRange(t, f.Offset, f.Length))381 }382 }383 fmt.Fprintf(w, "</table></p>\n")384 conf, err := t.GetConf()385 if err == nil {386 var useDht, dhtPassive, useTrackers, useWebseeds string387 if conf.UseDht == peer.ConfTrue {388 useDht = " checked"389 }390 if conf.DhtPassive == peer.ConfTrue {391 dhtPassive = " checked"392 }393 if conf.UseTrackers == peer.ConfTrue {394 useTrackers = " checked"395 }396 if conf.UseWebseeds == peer.ConfTrue {397 useWebseeds = " checked"398 }399 fmt.Fprintf(w, "<form action=\"/?q=set-torrent\" method=\"post\">\n")400 if dht.Available() {401 fmt.Fprintf(w, "<input type=\"checkbox\" id=\"use-dht-%v\" name=\"use-dht\"%v/><label for=\"use-dht-%v\">Use DHT</label> ", t.Hash, useDht, t.Hash)402 fmt.Fprintf(w, "<input type=\"checkbox\" id=\"dht-passive-%v\" name=\"dht-passive\"%v/><label for=\"dht-passive-%v\">Passive DHT</label> ", t.Hash, dhtPassive, t.Hash)403 }404 fmt.Fprintf(w, "<input type=\"checkbox\" id=\"use-trackers-%v\" name=\"use-trackers\"%v/><label for=\"use-trackers-%v\">Use trackers (%v)</label> ", t.Hash, useTrackers, t.Hash, stats.NumTrackers)405 fmt.Fprintf(w, "<input type=\"checkbox\" id=\"use-webseeds-%v\" name=\"use-webseeds\"%v/><label for=\"use-webseeds-%v\">Use webseeds (%v)</label> ", t.Hash, useWebseeds, t.Hash, stats.NumWebseeds)406 fmt.Fprintf(w, "<button type=\"submit\" name=\"hash\" value=\"%v\">Set</button></form>\n", t.Hash)407 }408 fmt.Fprintf(w, "<form action=\"/?q=delete\" class=\"delete-form\" method=\"post\"><button type=\"submit\" name=\"hash\" value=\"%v\">Delete</button></form>\n",409 t.Hash)410 return nil411}412func torrents(w http.ResponseWriter, r *http.Request) {413 ctx := r.Context()414 done := header(w, r, "STorrent")415 if done {416 return417 }418 fmt.Fprintf(w, "<form action=\"/?q=add\" method=\"post\">Magnet or URL: <input type=\"text\" name=\"url\"/> <input type=\"submit\"/></form> ")419 fmt.Fprintf(w, "<form action=\"/?q=set\" method=\"post\">Idle download: <input type=\"text\" name=\"idle\"/> Upload: <input type=\"text\" name=\"upload\"/> <input type=\"submit\"/></form>\n")420 fmt.Fprintf(w, "<p>Download %.0f/%.0f, upload %.0f/%.0f (unchoking %v), ",421 peer.DownloadEstimator.Estimate(), config.IdleRate(),422 peer.UploadEstimator.Estimate(), config.UploadRate(),423 peer.NumUnchoking())424 if dht.Available() {425 g4, g6, d4, d6, i4, i6 := dht.Count()426 fmt.Fprintf(w, "DHT %v+%v/%v %v+%v/%v, ",427 g4, i4, g4+d4,428 g6, i6, g6+d6)429 }430 fmt.Fprintf(w, "%v/%v bytes allocated.</p>\n",431 alloc.Bytes(), config.MemoryHighMark())432 var tors []*tor.Torrent433 tor.Range(func(k hash.Hash, t *tor.Torrent) bool {434 tors = append(tors, t)435 return true436 })437 sort.Slice(tors, func(i, j int) bool {438 return tors[i].Name < tors[j].Name ||439 (tors[i].Name == tors[j].Name &&440 bytes.Compare(tors[i].Hash, tors[j].Hash) < 0)441 })442 for _, t := range tors {443 err := torrentEntry(ctx, w, t, path.Path(nil))444 if err != nil {445 return446 }447 }448 footer(w)449}450func peers(w http.ResponseWriter, r *http.Request, t *tor.Torrent) {451 ps, err := t.GetPeers()452 if err != nil {453 if errors.Is(err, tor.ErrTorrentDead) {454 http.NotFound(w, r)455 } else {456 http.Error(w, err.Error(),457 http.StatusInternalServerError)458 }459 return460 }461 kps, err := t.GetKnowns()462 if err != nil {463 if errors.Is(err, tor.ErrTorrentDead) {464 http.NotFound(w, r)465 } else {466 http.Error(w, err.Error(),467 http.StatusInternalServerError)468 }469 return470 }471 done := header(w, r, "Peers for "+t.Name)472 if done {473 return474 }475 sort.Slice(ps, func(i, j int) bool {476 return bytes.Compare(ps[i].Id, ps[j].Id) < 0477 })478 fmt.Fprintf(w, "<p><table>\n")479 for _, p := range ps {480 hpeer(w, p, t)481 }482 fmt.Fprintf(w, "</table></p>\n")483 trackers := t.Trackers()484 if len(trackers) > 0 {485 fmt.Fprintf(w, "<p><table>\n")486 for i, tl := range trackers {487 for _, tt := range tl {488 state := ""489 st, err := tt.GetState()490 if st == tracker.Error && err != nil {491 state = fmt.Sprintf("(%v)", err)492 } else if st != tracker.Idle {493 state = fmt.Sprintf("(%v)", st.String())494 }495 fmt.Fprintf(w, "<tr><td>%v</td><td>%v</td></tr>\n",496 tt.URL(), state)497 }498 if i+1 < len(trackers) {499 fmt.Fprintf(w, "<tr></tr>\n")500 }501 }502 fmt.Fprintf(w, "</table></p>\n")503 }504 wss := t.Webseeds()505 if len(wss) > 0 {506 fmt.Fprintf(w, "<p><table>\n")507 for _, ws := range t.Webseeds() {508 cnt := ""509 count := ws.Count()510 if count > 0 {511 cnt = fmt.Sprintf("%v", count)512 }513 fmt.Fprintf(w, "<tr><td>%v</td><td>%v</td><td>%.0f</td>",514 ws.URL(), cnt, ws.Rate())515 }516 fmt.Fprintf(w, "</table></p>\n")517 }518 sort.Slice(kps, func(i, j int) bool {519 v41 := kps[i].Addr.IP.To4()520 v42 := kps[j].Addr.IP.To4()521 var a1, a2 []byte522 if v41 == nil && v42 != nil {523 return true524 } else if v41 != nil && v42 == nil {525 return false526 } else if v41 != nil && v42 != nil {527 a1 = v41528 a2 = v42529 } else {530 a1 = kps[i].Addr.IP.To16()531 a2 = kps[j].Addr.IP.To16()532 }533 c := bytes.Compare(a1, a2)534 if c < 0 {535 return true536 } else if c > 0 {537 return false538 }539 return kps[i].Addr.Port < kps[j].Addr.Port540 })541 fmt.Fprintf(w, "<p><table>\n")542 for _, k := range kps {543 hknown(w, &k, t)544 }545 fmt.Fprintf(w, "</table></p>\n")546 footer(w)547}548func parseId(id []byte) string {549 if id[0] == '-' && id[7] == '-' {550 return string(id[1:7])551 }552 return ""553}554func hpeer(w http.ResponseWriter, p *peer.Peer, t *tor.Torrent) {555 kp, _ := t.GetKnown(p.Id, p.IP, p.GetPort())556 var addr string557 if p.Port == 0 {558 if kp != nil {559 addr = kp.Addr.String()560 } else {561 addr = p.IP.String()562 }563 } else {564 a := net.TCPAddr{IP: p.IP, Port: p.GetPort()}565 addr = a.String()566 }567 fmt.Fprintf(w, "<tr><td>%v</td>", addr)568 stats := p.GetStats()569 if stats == nil {570 fmt.Fprintf(w, "<td><em>(dead)</em></td></tr>\n")571 return572 }573 var prefix, suffix string574 if !stats.Unchoked {575 prefix = "("576 suffix = ")"577 }578 qlen := stats.Qlen - stats.Rlen579 if qlen != 0 {580 fmt.Fprintf(w, "<td>%v%v+%v%v</td>",581 prefix, stats.Rlen, qlen, suffix)582 } else if stats.Rlen > 0 {583 fmt.Fprintf(w, "<td>%v%v%v</td>", prefix, stats.Rlen, suffix)584 } else if stats.Unchoked {585 fmt.Fprintf(w, "<td>0</td>")586 } else if stats.AmInterested {587 fmt.Fprintf(w, "<td>&#183;</td>")588 } else {589 fmt.Fprintf(w, "<td></td>")590 }591 fmt.Fprintf(w, "<td>%.0f/%.0f</td>", stats.AvgDownload, stats.Download)592 var zero time.Time593 if stats.AmUnchoking {594 fmt.Fprintf(w, "<td>%v</td>", stats.Ulen)595 } else if stats.Interested {596 if stats.UnchokeTime.Equal(zero) {597 fmt.Fprintf(w, "<td>(&#8734;s)</td>")598 } else {599 fmt.Fprintf(w, "<td>(%vs)</td>",600 int((time.Since(stats.UnchokeTime)+601 time.Second/2)/time.Second))602 }603 } else {604 fmt.Fprintf(w, "<td></td>")605 }606 fmt.Fprintf(w, "<td>%.0f</td>", stats.Upload)607 if stats.Rtt != 0 || stats.Rttvar != 0 {608 fmt.Fprintf(w, "<td>%.0f&#177;%.0f</td>",609 float64(stats.Rtt)/float64(time.Millisecond),610 float64(stats.Rttvar)/float64(time.Millisecond))611 } else {612 fmt.Fprintf(w, "<td></td>")613 }614 var scount string615 if t.Pieces.PieceSize() > 0 {616 count := (t.Pieces.Length() +617 int64(t.Pieces.PieceSize()) - 1) /618 int64(t.Pieces.PieceSize())619 scount = fmt.Sprintf("/%v", count)620 } else {621 scount = ""622 }623 flags := ""624 if stats.HasProxy {625 flags += "P"626 }627 if p.Incoming {628 flags += "I"629 }630 if p.Encrypted() {631 flags += "E"632 }633 if stats.AmUnchoking {634 flags += "U"635 } else if stats.Interested {636 flags += "u"637 }638 if stats.Seed {639 flags += "S"640 } else if stats.UploadOnly {641 flags += "s"642 }643 fmt.Fprintf(w, "<td>%v%v</td><td>%v</td>",644 stats.PieceCount, scount, flags)645 if stats.NumPex > 0 {646 fmt.Fprintf(w, "<td>%v</td>", stats.NumPex)647 } else {648 fmt.Fprintf(w, "<td></td>")649 }650 var version string651 if kp != nil {652 version = kp.Version653 }654 if version == "" {655 version = parseId(p.Id)656 }657 fmt.Fprintf(w, "<td>%v</td>", html.EscapeString(version))658 fmt.Fprintf(w, "<td>%v</td></tr>", p.Id)659}660func recent(tm time.Time) bool {661 return time.Since(tm) < 35*time.Minute662}663func hknown(w http.ResponseWriter, kp *known.Peer, t *tor.Torrent) {664 buf := new(bytes.Buffer)665 if kp.Attempts > 0 {666 fmt.Fprintf(buf, "%v, ", kp.Attempts)667 }668 if recent(kp.SeenTime) || recent(kp.ActiveTime) {669 fmt.Fprintf(buf, "Seen, ")670 }671 if recent(kp.HeardTime) {672 fmt.Fprintf(buf, "Heard, ")673 }674 if recent(kp.TrackerTime) {675 fmt.Fprintf(buf, "T, ")676 }677 if recent(kp.DHTTime) {678 fmt.Fprintf(buf, "DHT, ")679 }680 if recent(kp.PEXTime) {681 fmt.Fprintf(buf, "PEX, ")682 }683 if kp.Bad() {684 fmt.Fprintf(buf, "Bad, ")685 }686 var flags string687 if buf.Len() > 2 {688 b := buf.Bytes()689 flags = string(b[0 : len(b)-2])690 } else {691 flags = buf.String()692 }693 fmt.Fprintf(w, "<tr><td>%v</td><td>%v</td><td>%v</td><td>%v</td></tr>\n",694 kp.Addr.String(), flags, html.EscapeString(kp.Version), kp.Id)695}696func torfile(w http.ResponseWriter, r *http.Request) {697 path := r.URL.Path698 if path[0] != '/' || len(path) <= 41 {699 http.NotFound(w, r)700 return701 }702 hash := hash.Parse(path[1:41])703 if hash == nil {704 http.NotFound(w, r)705 return706 }707 t := tor.Get(hash)708 if t == nil {709 http.NotFound(w, r)710 return711 }712 if !t.InfoComplete() {713 http.Error(w, "torrent metadata incomplete",714 http.StatusGatewayTimeout)715 return716 }717 w.Header().Set("content-type", "application/x-bittorrent")718 if t.CreationDate > 0 {719 cdate := time.Unix(t.CreationDate, 0)720 w.Header().Set("last-modified",721 cdate.UTC().Format(http.TimeFormat))722 }723 if r.Method == "HEAD" {724 return725 }726 err := tor.WriteTorrent(w, t)727 if err != nil {728 panic(http.ErrAbortHandler)729 }730}731func m3uentry(w http.ResponseWriter, host string, hash hash.Hash, path path.Path) {732 fmt.Fprintf(w, "#EXTINF:-1,%v\n",733 strings.Replace(path[len(path)-1], ",", "", -1))734 fmt.Fprintf(w, "http://%v/%v/%v\n",735 host, hash, pathUrl(path))736}737func playlist(w http.ResponseWriter, r *http.Request, hash hash.Hash, dir path.Path) {738 t := tor.Get(hash)739 if t == nil {740 http.NotFound(w, r)741 return742 }743 if !t.InfoComplete() {744 http.Error(w, "torrent metadata incomplete",745 http.StatusGatewayTimeout)746 return747 }748 if t.Files == nil {749 if len(dir) > 0 {750 http.NotFound(w, r)751 return752 }753 } else {754 var found bool755 for _, f := range t.Files {756 if f.Path.Within(dir) {757 found = true758 break759 }760 }761 if !found {762 http.NotFound(w, r)763 return764 }765 }766 w.Header().Set("content-type", "application/vnd.apple.mpegurl")767 if t.CreationDate > 0 {768 cdate := time.Unix(t.CreationDate, 0)769 w.Header().Set("last-modified",770 cdate.UTC().Format(http.TimeFormat))771 }772 if r.Method == "HEAD" {773 return774 }775 fmt.Fprintf(w, "#EXTM3U\n")776 if t.Files == nil {777 m3uentry(w, r.Host, hash, path.Parse(t.Name))778 } else {779 a := make([]int, len(t.Files))780 for i := range a {781 a[i] = i782 }783 sort.Slice(a, func(i, j int) bool {784 return t.Files[a[i]].Path.Less(t.Files[a[j]].Path)785 })786 for _, i := range a {787 path := t.Files[i].Path788 if path.Within(dir) {789 m3uentry(w, r.Host, hash, path)790 }791 }792 }793}794func file(w http.ResponseWriter, r *http.Request, hash hash.Hash, path path.Path) {795 t := tor.Get(hash)796 if t == nil {797 http.NotFound(w, r)798 return799 }800 if !t.InfoComplete() {801 http.Error(w, "torrent metadata incomplete",802 http.StatusGatewayTimeout)803 return804 }805 offset, length, etag, err := fileParms(t, hash, path)806 if err != nil {807 if os.IsNotExist(err) {808 http.NotFound(w, r)809 return810 } else {811 http.Error(w, err.Error(),812 http.StatusInternalServerError)813 return814 }815 }816 var ctime time.Time817 if t.CreationDate > 0 {818 ctime = time.Unix(t.CreationDate, 0)819 }820 w.Header().Set("etag", etag)821 reader := t.NewReader(r.Context(), offset, length)822 defer reader.Close()823 http.ServeContent(w, r, path.String(), ctime, reader)824}825func fileParms(t *tor.Torrent, hash hash.Hash, pth path.Path) (offset int64, length int64, etag string, err error) {826 var file *tor.Torfile827 if t.Files == nil {828 if len(pth) != 1 || pth[0] != t.Name {829 err = os.ErrNotExist830 return831 }832 offset = 0833 length = t.Pieces.Length()834 } else {835 for _, f := range t.Files {836 if pth.Equal(f.Path) {837 file = &f838 break839 }840 }841 if file == nil {842 err = os.ErrNotExist843 return844 }845 offset = file.Offset846 length = file.Length847 }848 etag = fmt.Sprintf("\"%v-%v\"", hash.String(), offset)849 return850}...

Full Screen

Full Screen

edit.go

Source:edit.go Github

copy

Full Screen

1package handlers2import (3 "fmt"4 "net/http"5 "strconv"6 "github.com/craigjperry2/mingo/internal/app/mingo/config"7 "github.com/craigjperry2/mingo/internal/app/mingo/database"8)9// Handle CRUD requests to the Person resource10type EditHandler struct {11 db *database.Db12}13func NewEditHandler() EditHandler {14 return EditHandler{config.GetInstance().GetDatabase()}15}16func (h EditHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {17 switch req.Method {18 case http.MethodPut:19 if req.URL.Path != "/edit" {20 http.NotFound(w, req)21 return22 }23 id, err := strconv.Atoi(req.URL.Query().Get("id"))24 if err != nil {25 http.NotFound(w, req)26 return27 }28 req.ParseForm()29 p, _ := h.db.Update(id, req.FormValue("name"), req.FormValue("location"))30 fmt.Fprintf(w, `<tr> <td>%d</td> <td>%s</td> <td>%s</td> <td><div class="buttons are-small"><button class="button is-info" hx-get="/edit?id=%d">Edit</button><button class="button is-danger" hx-delete="/crud?id=%d">Delete</button></div></td> </tr>`, p.Id, p.Name, p.Location, p.Id, p.Id)31 case http.MethodPost:32 if req.URL.Path != "/edit" {33 http.NotFound(w, req)34 return35 }36 req.ParseForm()37 p, _ := h.db.Insert(req.FormValue("name"), req.FormValue("location"))38 fmt.Fprintf(w, `<tr hx-swap-oob="afterbegin:.tablebody" hx-swap="outerHTML"><td>%d</td> <td>%s</td> <td>%s</td> <td><div class="buttons are-small"><button class="button is-info" hx-get="/edit?id=%d">Edit</button><button class="button is-danger" hx-delete="/crud?id=%d">Delete</button></div></td> </tr> <tr> <td></td> <td><input name="name" placeholder="name"></td> <td><input name="location" placeholder="location"></td> <td><div class="buttons are-small"><button class="button is-info" hx-post="/edit" hx-include="closest tr" hx-target="closest tr" hx-swap="outerHTML">Add</button></div></td> </tr>`, p.Id, p.Name, p.Location, p.Id, p.Id)39 default: // GET40 if req.URL.Path != "/edit" {41 http.NotFound(w, req)42 return43 }44 id, err := strconv.Atoi(req.URL.Query().Get("id"))45 if err != nil {46 http.NotFound(w, req)47 return48 }49 row, _ := h.db.Get(id)50 fmt.Fprintf(w, `<tr> <td>%d</td> <td><input name='name' value='%s'></td> <td><input name='location' value='%s'></td> <td><div class="buttons are-small"><button class="button is-info">Cancel</button><button class="button is-danger" hx-put="/edit?id=%d" hx-include="closest tr">Save</button></div></td> </tr>`, row.Id, row.Name, row.Location, row.Id)51 }52}...

Full Screen

Full Screen

crud.go

Source:crud.go Github

copy

Full Screen

1package handlers2import (3 "fmt"4 "net/http"5 "strconv"6 "github.com/craigjperry2/mingo/internal/app/mingo/config"7 "github.com/craigjperry2/mingo/internal/app/mingo/database"8)9// Handle CRUD requests to the Person resource10type CrudHandler struct {11 db *database.Db12}13func NewCrudHandler() CrudHandler {14 return CrudHandler{config.GetInstance().GetDatabase()}15}16func (h CrudHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {17 switch req.Method {18 case http.MethodDelete:19 if req.URL.Path != "/crud" {20 http.NotFound(w, req)21 return22 }23 id, err := strconv.Atoi(req.URL.Query().Get("id"))24 if err != nil {25 http.NotFound(w, req)26 return27 }28 h.db.Delete(id)29 case http.MethodPut:30 if req.URL.Path != "/crud" {31 http.NotFound(w, req)32 return33 }34 default: // GET35 if req.URL.Path != "/crud" {36 http.NotFound(w, req)37 return38 }39 offset, err := strconv.Atoi(req.URL.Query().Get("offset"))40 if err != nil || offset < 0 {41 offset = 042 }43 limit, err := strconv.Atoi(req.URL.Query().Get("limit"))44 if err != nil || limit < 1 {45 limit = 146 }47 all, _ := h.db.GetAll(offset, limit)48 for _, p := range all {49 fmt.Fprintf(w, `<tr> <td>%d</td> <td>%s</td> <td>%s</td> <td><div class="buttons are-small"><button class="button is-info" hx-get="/edit?id=%d">Edit</button><button class="button is-danger" hx-delete="/crud?id=%d">Delete</button></div></td> </tr>`, p.Id, p.Name, p.Location, p.Id, p.Id)50 }51 if limit == len(all) {52 fmt.Fprintf(w, `<tr id="replaceMe"> <td colspan="4" class="has-text-centered"> <button class="button is-link" hx-get="/crud?limit=%d&offset=%d" hx-target="#replaceMe" hx-swap="outerHTML" hx-confirm="unset"> Load More... <span class="htmx-indicator is-transparent"> <span class="icon-text"> <span class="icon"> <i class="fas fa-spinner"></i> </span> </span> </span> </button> </td> </tr>`, limit, all[len(all)-1].Id)53 }54 }55}...

Full Screen

Full Screen

notFound

Using AI Code Generation

copy

Full Screen

1import (2func notFound(w http.ResponseWriter, r *http.Request) {3 t, _ := template.ParseFiles("404.html")4 t.Execute(w, nil)5}6func main() {7 http.HandleFunc("/", notFound)8 http.ListenAndServe(":8080", nil)9}10import (11func notFound(w http.ResponseWriter, r *http.Request) {12 t, _ := template.ParseFiles("404.html")13 t.Execute(w, nil)14}15func main() {16 http.HandleFunc("/", notFound)17 http.ListenAndServe(":8080", nil)18}19import (20func notFound(w http.ResponseWriter, r *http.Request) {21 t, _ := template.ParseFiles("404.html")22 t.Execute(w, nil)23}24func main() {25 http.Handle("/", http.HandlerFunc(notFound))26 http.ListenAndServe(":8080", nil)27}28import (29func notFound(w http.ResponseWriter, r *http.Request) {30 t, _ := template.ParseFiles("404.html")31 t.Execute(w, nil)32}33func main() {34 http.Handle("/", http.HandlerFunc(notFound))35 http.ListenAndServe(":8080", nil)36}

Full Screen

Full Screen

notFound

Using AI Code Generation

copy

Full Screen

1import (2func (m td) ServeHTTP(w http.ResponseWriter, req *http.Request) {3 fmt.Println(req.URL.Path)4 if req.URL.Path == "/dog/" {5 fmt.Fprintln(w, "doggy doggy doggy")6 } else if req.URL.Path == "/cat/" {7 fmt.Fprintln(w, "kitty kitty kitty")8 } else {9 fmt.Fprintln(w, "not found")10 }11}12func main() {13 http.ListenAndServe(":8080", d)14}15import (16func (m td) ServeHTTP(w http.ResponseWriter, req *http.Request) {17 fmt.Println(req.URL.Path)18 if req.URL.Path == "/dog/" {19 fmt.Fprintln(w, "doggy doggy doggy")20 } else if req.URL.Path == "/cat/" {21 fmt.Fprintln(w, "kitty kitty kitty")22 }23}24func main() {25 http.ListenAndServe(":8080", d)26}27import (28func (m td) ServeHTTP(w http.ResponseWriter, req *http.Request) {29 fmt.Println(req.URL.Path)30 if req.URL.Path == "/dog/" {31 fmt.Fprintln(w, "doggy doggy doggy")32 } else if req.URL.Path == "/cat/" {33 fmt.Fprintln(w, "kitty kitty kitty")34 } else {35 http.NotFound(w, req)36 }37}38func main() {39 http.ListenAndServe(":8080", d)40}41import (42func (m td) ServeHTTP(w http.ResponseWriter, req *http.Request) {43 fmt.Println(req.URL.Path)44 if req.URL.Path == "/dog/" {45 fmt.Fprintln(w, "doggy doggy doggy")46 } else if req.URL.Path == "/cat/" {47 fmt.Fprintln(w, "kitty kitty kitty")48 } else {49 http.Error(w

Full Screen

Full Screen

notFound

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 c = max(a, b)4 fmt.Printf("Max value is : %d5}6func max(num1, num2 int) int {7 if (num1 > num2) {8 } else {9 }10}11import (12func main() {13 ret = max(a, b)14 fmt.Printf("Max value is : %d15}16func max(num1, num2 int) int {17 if (num1 > num2) {18 } else {19 }20}21import (22func main() {23 ret = max(a, b)24 fmt.Printf("Max value is : %d25}26func max(num1, num2 int) int {27 if (num1 > num2) {28 } else {29 }30}31import (32func main() {33 ret = max(a, b)34 fmt.Printf("Max value is : %d35}36func max(num1, num2 int) int {37 if (num1 > num2) {38 } else {39 }40}

Full Screen

Full Screen

notFound

Using AI Code Generation

copy

Full Screen

1func main() {2 td := &td{}3 td.notFound()4}5func main() {6 td := &td{}7 td.notFound()8}9func main() {10 td := &td{}11 td.notFound()12}13func main() {14 td := &td{}15 td.notFound()16}17func main() {18 td := &td{}19 td.notFound()20}21func main() {22 td := &td{}23 td.notFound()24}25func main() {26 td := &td{}27 td.notFound()28}29func main() {30 td := &td{}31 td.notFound()32}33func main() {34 td := &td{}35 td.notFound()36}37func main() {38 td := &td{}39 td.notFound()40}41func main() {42 td := &td{}43 td.notFound()44}45func main() {46 td := &td{}47 td.notFound()48}49func main() {50 td := &td{}51 td.notFound()52}53func main() {54 td := &td{}55 td.notFound()56}57func main() {58 td := &td{}59 td.notFound()60}

Full Screen

Full Screen

notFound

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {4 fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))5 })6 http.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {7 fmt.Fprintf(w, "test")8 })9 http.HandleFunc("/notfound", func(w http.ResponseWriter, r *http.Request) {10 http.NotFound(w, r)11 })12 http.HandleFunc("/redirect", func(w http.ResponseWriter, r *http.Request) {13 })14 http.HandleFunc("/form", func(w http.ResponseWriter, r *http.Request) {15 w.Header().Set("Content-Type", "text/html; charset=utf-8")16 switch r.Method {17 fmt.Fprintf(w, `<form method="POST" action="/form">18 r.ParseForm()19 fmt.Fprintf(w, "Post from website! r.PostFrom = %v20 for k, v := range r.PostForm {21 fmt.Fprintf(w, "k = %s, v = %s22 }23 }24 })25 http.HandleFunc("/upload", func(w http.ResponseWriter, r *http.Request) {26 fmt.Println("method:", r.Method)27 if r.Method == "GET" {28 curtime := time.Now().Unix()29 h := md5.New()30 io.WriteString(h, strconv.FormatInt(curtime, 10))31 token := fmt.Sprintf("%x", h.Sum(nil))32 fmt.Println("token:", token)33 t, _ := template.ParseFiles("upload.gtpl")34 t.Execute(w, token)35 } else {36 r.ParseMultipartForm(32 << 20)37 file, handler, err := r.FormFile("uploadfile")38 if err != nil {39 fmt.Println(err)40 }41 defer file.Close()42 fmt.Fprintf(w, "%v", handler.Header)43 f, err := os.OpenFile("./test/"+handler.Filename, os

Full Screen

Full Screen

notFound

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 td := new(xlsx.Td)4 fmt.Println(td.NotFound())5}6import (7func main() {8 td := new(xlsx.Td)9 fmt.Println(td.Value())10}11import (12func main() {13 td := new(xlsx.Td)14 style := new(xlsx.Style)15 fmt.Println(td.SetStyle(style))16}17import (18func main() {19 td := new(xlsx.Td)20 fmt.Println(td.SetFormula("test"))21}22import (23func main() {24 td := new(xlsx.Td)25 richText := new(xlsx.RichText)26 fmt.Println(td.SetRichText(richText))27}28import (29func main() {30 td := new(xlsx.Td)31 hyperlink := new(xlsx.Hyperlink)32 fmt.Println(td.SetHyperlink(hyperlink))33}34import (35func main() {36 td := new(xlsx.Td)37 comment := new(xlsx.Comment)38 fmt.Println(td.SetComment(comment))39}40import (41func main() {42 td := new(xlsx.Td)43 fmt.Println(td.SetMerge("test"))44}

Full Screen

Full Screen

notFound

Using AI Code Generation

copy

Full Screen

1import (2type td struct {3}4func (t td) notFound() {5 fmt.Println("Not Found")6}7func main() {8 t := td{"test"}9 v := reflect.ValueOf(t)10 m := v.MethodByName("notFound")11 if m.IsValid() {12 args := []reflect.Value{}13 m.Call(args)14 } else {15 fmt.Println("Method not found")16 }17}18import (19type td struct {20}21func (t td) notFound() {22 fmt.Println("Not Found")23}24func main() {25 t := td{"test"}26 v := reflect.ValueOf(t)27 m := v.MethodByName("notFound")28 if m.IsValid() {29 args := []reflect.Value{}30 m.Call(args)31 } else {32 fmt.Println("Method not found")33 }34}35import (36type td struct {37}38func (t td) notFound() {39 fmt.Println("Not Found")40}41func main() {42 t := td{"test"}43 v := reflect.ValueOf(t)44 m := v.MethodByName("notFound")45 if m.IsValid() {46 args := []reflect.Value{}47 m.Call(args)48 } else {49 fmt.Println("Method not found")50 }51}52import (53type td struct {54}55func (t td) notFound() {56 fmt.Println("Not Found")57}58func main() {59 t := td{"test"}60 v := reflect.ValueOf(t)61 m := v.MethodByName("notFound")62 if m.IsValid() {63 args := []reflect.Value{}64 m.Call(args)65 } else {66 fmt.Println("Method not found")67 }68}69import (70type td struct {71}72func (t td)

Full Screen

Full Screen

notFound

Using AI Code Generation

copy

Full Screen

1import "fmt"2type testD interface {3 notFound() string4}5type testDImpl struct {6}7func (td *testDImpl) notFound() string {8}9func main() {10 td = &testDImpl{name: "test"}11 fmt.Println(td.notFound())12}

Full Screen

Full Screen

notFound

Using AI Code Generation

copy

Full Screen

1func main() {2 td := &td{}3 td.notFound()4}5func main() {6 td := &td{}7 td.notFound()8}9func main() {10 td := &td{}11 td.notFound()12}13func main() {14 td := &td{}15 td.notFound()16}17func main() {18 td := &td{}19 td.notFound()20}21func main() {22 td := &td{}23 td.notFound()24}25func main() {26 td := &td{}27 td.notFound()28}29func main() {30 td := &td{}31 td.notFound()32}33func main() {34 td := &td{}35 td.notFound()36}37func main() {38 td := &td{}39 td.notFound()40}41func main() {42 td := &td{}43 td.notFound()44}

Full Screen

Full Screen

notFound

Using AI Code Generation

copy

Full Screen

1import (2type td struct {3}4func main() {5 http.HandleFunc("/", foo)6 http.ListenAndServe(":8080", nil)7}8func foo(w http.ResponseWriter, r *http.Request) {9 tpl, err := template.ParseFiles("index.gohtml")10 if err != nil {11 log.Fatalln(err)12 }13 err = tpl.Execute(w, nil)14 if err != nil {15 log.Fatalln(err)16 }17}18func notFound(w http.ResponseWriter, r *http.Request) {19 tpl, err := template.ParseFiles("notFound.gohtml")20 if err != nil {21 log.Fatalln(err)22 }23 err = tpl.Execute(w, nil)24 if err != nil {25 log.Fatalln(err)26 }27}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Go-testdeep automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful