Apostrophe changes after sanitizing word - html

package main
import (
"log"
"github.com/microcosm-cc/bluemonday"
)
func main() {
c := "hello doesn't work 😖"
p := bluemonday.UGCPolicy()
log.Println(p.Sanitize(c))
}
the expected output should be
hello doesn't work 😖
instead i receive
hello doesn't work 😖
I try by using allowlist with regexp but it doesn't work

That's not really a change in the context of HTML, as you can see below:
<div>hello doesn't work 😖</div>
<div>hello doesn't work 😖</div>

Related

go JSON nightmare - Is there a simple [POSH] ConvertFrom-Json equivalent?

In powershell, if I make a REST call and receive any kind of json response, I can easily $json | ConvertFrom-Json into a proper object so I can make modifications, render specific values, whatever.
It seems like in Go I have to either define a struct, or "dynamically" convert using a map[string]interface{}.
The issue with a struct is that I am writing a rest handler for a platform that, depending on the endpoint, serves wildly different JSON responses, like most REST APIs. I don't want to define a struct for all of the dozens of possible responses.
The problem with map[string]interface{} is that it pollutes the data by generating a string with a bunch of ridiculous 'map' prefixes and unwanted [brackets].
ala: [map[current_user_role:admin id:1]]
Is there a way to convert a JSON response like:
{
"current_user_role": "admin",
"id": 1
}
To return a basic:
current_user_role: admin
id: 1
... WITHOUT defining a struct?
Your approach of using a map is right if you don't wish to specify the structure of the data you're receiving. You don't like how it is output from fmt.Println, but I suspect you're confusing the output format with the data representation. Printing them out in the format you find acceptable takes a couple of lines of code, and is not as convenient as in python or powershell, which you may find annoying.
Here's a working example (playground link):
package main
import (
"encoding/json"
"fmt"
"log"
)
var data = []byte(`{
"current_user_role": "admin",
"id": 1
}`)
func main() {
var a map[string]interface{}
if err := json.Unmarshal(data, &a); err != nil {
log.Fatal(err)
}
for k, v := range a {
fmt.Printf("%s: %v\n", k, v)
}
}

Output a simple json file to a rest api with golang

This is my first go project. All I want to do is read a file.json on my server, then make it available to others via a REST API. But I'm getting errors. Here's what I have so far.
main.go
package main
import (
"encoding/json"
"github.com/gorilla/mux"
"log"
"net/http"
"io/ioutil"
"fmt"
)
func GetDetail(w http.ResponseWriter, r *http.Request) {
b,_ := ioutil.ReadFile("file.json");
rawIn := json.RawMessage(string(b))
var objmap map[string]*json.RawMessage
err := json.Unmarshal(rawIn, &objmap)
if err != nil {
fmt.Println(err)
}
fmt.Println(objmap)
json.NewEncoder(w).Encode(objmap)
}
func main() {
router := mux.NewRouter()
router.HandleFunc("/detail", GetDetail).Methods("GET")
log.Fatal(http.ListenAndServe(":8000", router))
}
file.json
{
favourite_color:"blue",
attribute:{density:23,allergy:"peanuts",locations:["USA","Canada","Jamaica"]},
manufacture_year:1998
}
When I run go build; ./sampleproject, then go to my web browser at http://localhost:8000/detail, I get the error message:
invalid character 'f' looking for beginning of object key string
map[]
I've tried a few marshal methods, but they all give me different errors. I just need a working example to study from to better understand how all this works.
I should also mention that file.json does not have a fixed schema. It can change drastically at any minute to have a random set of data.
How do I get around the error invalid character f message and get my file.json to render at http://localhost:8000/detail?
As cerise mentioned, it's just formatting error in the JSON file. Must quote all properties.
Then the rest of the code works

GoLang - XmlPath Selectors with HTML

I am looking at the documented example here, but it is iterating purely over an XML tree, and not HTML. Therefore, I am still partly confused.
For example, if I wanted to find a specific meta tag within the head tag by name, it seems I cannot? Instead, I need to find it by the order it is in the head tag. In this case, I want the 8th meta tag, which I assume is:
headTag, err := getByID(xmlroot, "/head/meta[8]/")
But of course, this is using a getByID function for a tag name - which I don't believe will work. What is the full list of "getBy..." commands?
Then, the problem is, how do I access the meta tag's contents? The documentation only provides examples for the inner tag node content. However, will this example work?:
resp.Query = extractValue(headTag, #content)
The # selector confuses me, is this appropriate for this case?
In other words:
Is there a proper HTML example available?
Is there a list of correct selectors for IDs, Tags, etc?
Can Tags be found by name, and content extracted from its inner content tag?
Thank you very much!
I know this answer is late, but I still want to recommend an htmlquery package that is simple and powerful, based on XPath expressions*.
The below code based on #Time-Cooper example.
package main
import (
"fmt"
"github.com/antchfx/htmlquery"
)
func main() {
doc, err := htmlquery.LoadURL("https://example.com")
if err != nil {
panic(err)
}
s := htmlquery.Find(doc, "//meta[#name='viewport']")
if len(s) == 0 {
fmt.Println("could not find viewpoint")
return
}
fmt.Println(htmlquery.SelectAttr(s[0], "content"))
// alternative method,but simple more.
s2 := htmlquery.FindOne(doc, "//meta[#name='viewport']/#content")
fmt.Println(htmlquery.InnerText(s2))
}
XPath does not seem suitable here; you should be using goquery, which is designed for HTML.
Here is an example:
package main
import (
"fmt"
"github.com/PuerkitoBio/goquery"
)
func main() {
doc, err := goquery.NewDocument("https://example.com")
if err != nil {
panic(err)
}
s := doc.Find(`html > head > meta[name="viewport"]`)
if s.Length() == 0 {
fmt.Println("could not find viewpoint")
return
}
fmt.Println(s.Eq(0).AttrOr("content", ""))
}

Partial unescape html string

I have webapp. Go html template will escape all unsafe tag. Is there way to selectively escape a string? For instance, Google.com will highlight your search query and wrap it with <em> tag while all other html & javascript gets escaped. I have this:
package main
import (
"fmt"
"html/template"
)
func main() {
s := "<i>This should be escaped</i><strong>This should be in bold</strong>."
h := template.HTMLEscaper(s)
fmt.Println(h)
}
Right now everything gets escaped. I am aware you can do a template function with template.HTML(mystring) but how do I do that for part of a string?
thx!
EDIT:
I would like the final string to be:
<i>This should be escaped</i><strong>This should be in bold</strong>.
To be clear, I have tried creating a template function to highlight matches...the html I add gets escaped in the actual template ;(

Go Lang Return JSON

Still pretty new with Go. I'm trying to get go to essentially print a struct with the keys and values as close to json as possible.
The way I'm currently doing this is having GO on it's own server and whenever a get request is made, it returns the JSON. I would like to have GO as an executable on my primary Rails server and just return the JSON with something like Println (or whatever would make it stay in struct form). The problem is when I try to go this route, the keys from the struct aren't printed with it and I would basically have to add the keys as part of the return string.
Is there a simple way to do this with keeping the correct keys and values (and their types, so if the value is an array, keep the array)
Printing a struct as JSON to STDOUT is fairly straight forward in Go:
package main
import (
"encoding/json"
"fmt"
"log"
"os"
)
func main() {
foo := struct {
Hello string
JSON string
}{
Hello: "world",
JSON: "stuff",
}
fmt.Printf("foo struct : %+v\n", foo)
if err := json.NewEncoder(os.Stdout).Encode(foo); err != nil {
log.Fatal(err)
}
}
http://play.golang.org/p/wqqGJ1V_Zg
That program will output the following:
foo struct : {Hello:world JSON:stuff}
{"Hello":"world","JSON":"stuff"}
From your question I really didn't understand what you meant. In any case, if you wanted to print the struct as JSON or if you just wanted to print the struct as close to JSON as possible your answer is there.